package com.rpc.netty.groupChartNetty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * @author 何章怀晓 hezhanghuaixiao
 * @version V1.0
 * @desc
 */
public class GroupChartServer {

  private int port;


  public GroupChartServer(int port) {
    this.port = port;
  }


  //处理客户端请求
  public void run() {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {
      ServerBootstrap bootstrap = new ServerBootstrap();
      bootstrap.group(bossGroup, workerGroup)
          .channel(NioServerSocketChannel.class)
          .option(ChannelOption.SO_BACKLOG, 128)
          .childOption(ChannelOption.SO_KEEPALIVE, true)
          .childHandler(new ChannelInitializer<SocketChannel>() {


            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
              //获取pipeline
              ChannelPipeline pipeline = ch.pipeline();
              System.out.println("服务器端pipeline" + pipeline.hashCode());

              //管道中加入解码器和编码器
              pipeline.addLast("decoder", new StringDecoder());
              pipeline.addLast("encoder", new StringEncoder());
              pipeline.addLast(new GroupChartServerHandler());
            }
          });

      System.out.println("netty服务器启动.....");

      ChannelFuture future = bootstrap.bind(port).sync();
      future.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
          if (future.isDone()) {
            System.out.println("操作完成");
            if (future.isSuccess()) {
              System.out.println("successful");
            } else {
              System.out.println("fail");
            }
          }
        }
      });
      future.channel().closeFuture().sync();

      //获取异步状态

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      bossGroup.shutdownGracefully();
      workerGroup.shutdownGracefully();
    }


  }


  public static void main(String[] args) {

    new GroupChartServer(8888).run();


  }

}
